//
//  BSHotTableVC.m
//  BS
//
//  Created by lanou on 15/8/14.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#define kURL @"http://api.budejie.com/api/api_open.php?from=ios"

#define kURL1 @"http://api.budejie.com/api/api_open.php?appname=baisishequ&asid=0F302804-E0E8-43DE-A3EE-9B538B4654AE&client=iphone&device=ios%20%E8%AE%BE%E5%A4%87&from=ios&jbk=0&mac=&market=&openudid=5979ad73088ea5230ae9f104b993548b30416651&page=0&per=20&sub_flag=1&udid=&uid=15567628&ver=3.6.1"
#import "BSHotTableVC.h"

#import "LJRequestManagerBlock.h"

#import "BSListModel.h"

#import "BSTextCell.h"

#import "BSHeaderView.h"

#import "BSFooterView.h"

#import "BSVideoCell.h"

#import "BSImageCell.h"

#import "PlayerManger.h"

#import "SDImageCache.h"

#import "MJRefresh.h"

#import "BSDataBaseManager.h"

#import "BSVoiceCell.h"

#import "BSWebCell.h"
#import "CRToast.h"

#import "UMSocialDataService.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSnsService.h"
#import "UMSocial.h"
#import "BSUserSetting.h"
typedef NS_ENUM(NSInteger, RefreshType) {
    RefreshNew,
    RefreshMore,
    RefreshError//没有网的时候
};
@interface BSHotTableVC ()
{
    RefreshType _refreshType;
}

@property (nonatomic, strong)BSListModel *model;
@end

@implementation BSHotTableVC


- (void)addRefreshNew
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _refreshType = RefreshNew;
         [self.parameterDic setValue:@"1" forKey:@"page"];
        [self requestData:self.parameterDic];
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}


- (void)addRefreshMore
{
         // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _refreshType = RefreshMore;
        NSString *page = [self.parameterDic valueForKey:@"page"];
        NSInteger pageNew = [page integerValue] + 1;
        [self.parameterDic setValue:[NSString stringWithFormat:@"%ld",pageNew] forKey:@"page"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.parameterDic];
        [dic setValue:[[[self.dataSource lastObject] t] stringValue]forKey:@"maxtime"];
        [self requestData:dic];
    }];
}


-(NSMutableArray *)dataSource{

    if (_dataSource == nil) {
        _dataSource =[[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataSource;
}


- (void)requestData:(NSDictionary *)parameter{

   [LJRequestManagerBlock manager:GET requestWith:kURL1 dic:parameter finish:^(NSData *data) {
       //如果是刷新状态就直接重新set data 如果是加载状态 就将新老数据拼接起来存进去
       if (_refreshType == RefreshNew) {
//           NSLog(@"有网,正在刷新");
           [[BSDataBaseManager defaultManager] setData:data name:self.typeName withTableName:self.parameterDic[@"a"]];
       }
       [self parameterData:data];
   } error:^(NSError *error) {
       
       //如果错误,说明没有网 我们就将数据取出 这个时候我们要判断一下 如果是打开程序的时候就没有网 我们就将数据取出
       if([self.dataSource count] == 0){
     NSData *data = [[BSDataBaseManager defaultManager] dataWithName:self.typeName withTableName:self.parameterDic[@"a"]];
           [self parameterData:data];
//            NSLog(@"没有网,从数据库取数据");
       }
       else{
//           NSLog(@"没有网,我不处理");
           [self endRefreshing];
       }
   }];
    
}



- (void)parameterData:(NSData *)data{
    
 //程序第一次尽量的时候没有网,数据库里面也没有数据 所以会蹦,我们判断一下如果data为nil 直接返回
    if (data == nil) {
//        NSLog(@"即没有网 数据库也没有数据");
    [self endRefreshing];
        return;
    }
    if (_refreshType == RefreshNew) {
        self.dataSource = nil;
    }
     NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
    NSArray *listArray = dataDict[@"list"];
    for (NSDictionary *dict in listArray) {
        BSListModel *listModel = [[BSListModel alloc] init];
        [listModel setValuesForKeysWithDictionary:dict];
        [self.dataSource addObject:listModel];
    }
    [self endRefreshing];
    [self.tableView reloadData];
    
}

- (void)endRefreshing{
    
    if (_refreshType == RefreshNew) {
        [self.tableView.header endRefreshing];
        [self addRefreshMore];
    }
    if (_refreshType == RefreshMore) {
        [self.tableView.footer endRefreshing];
    }

}


- (void)test{

    if ([self.dataSource count]) {
        for (BSListModel *model in self.dataSource) {
            model.cellHeight = 0;
        }
    }
       [self.tableView reloadData];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"字体改变" object:nil];
    self.tableView.backgroundColor = [UIColor whiteColor];
    //第一次加载的时候就让他先插入一条记录,因为name是主键,所以重名就会插入失败
    [[BSDataBaseManager defaultManager] addDataName:self.typeName data:nil withTableName:self.parameterDic[@"a"]];
    
    [self addRefreshNew];
    [self.tableView registerNib:[UINib nibWithNibName:@"BSVideoCell" bundle:nil] forCellReuseIdentifier:@"videoCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BSTextCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BSImageCell" bundle:nil] forCellReuseIdentifier:@"imageCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BSVoiceCell" bundle:nil] forCellReuseIdentifier:@"voiceCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BSWebCell" bundle:nil] forCellReuseIdentifier:@"webCell"];
    [self.tableView registerClass:[BSHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.tableView registerClass:[BSFooterView class] forHeaderFooterViewReuseIdentifier:@"footer"];
}

- (void)didReceiveMemoryWarning {
//    NSLog(@"BSHotTableVC内存警告");
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return [self.dataSource count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BSListModel *model = self.dataSource[indexPath.section];
    self.model = self.dataSource[indexPath.section];
    if ([model.type isEqualToString:@"29"]) {
        BSTextCell *textCell = [tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
        textCell.model = model;
        return textCell;
    }
    if ([model.type isEqualToString:@"10"]) {
        BSImageCell *imageCell = [tableView dequeueReusableCellWithIdentifier:@"imageCell" forIndexPath:indexPath];
        imageCell.vc = self;
        imageCell.model = model;
        return imageCell;
    }
    if ([model.type isEqualToString:@"41"]) {
          BSVideoCell *videoCell = [tableView dequeueReusableCellWithIdentifier:@"videoCell" forIndexPath:indexPath];
        videoCell.model = model;
        videoCell.vc = self;
        return videoCell;
    }
    if ([model.type isEqualToString:@"31"]) {
        BSVoiceCell *voiceCell = [tableView dequeueReusableCellWithIdentifier:@"voiceCell" forIndexPath:indexPath];
        voiceCell.model = model;
        voiceCell.vc = self;
        return voiceCell;
    }
    if ([model.type isEqualToString:@"51"]){
        BSWebCell *webCell = [tableView dequeueReusableCellWithIdentifier:@"webCell" forIndexPath:indexPath];
        webCell.model = model;
        webCell.nav = self.navigationController;
        return webCell;
    }
    BSTextCell *textCell = [tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
    return textCell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BSListModel *model = self.dataSource[indexPath.section];
    if ([model.type isEqualToString:@"29"]) {
        return [BSTextCell heightOfCell:model];
    }
    if ([model.type isEqualToString:@"10"]) {
        return [BSImageCell heightOfCell:model];
    }
    if ([model.type isEqualToString:@"41"]) {
        return [BSVideoCell heightOfCell:model];
    }
    if ([model.type isEqualToString:@"31"]) {
        return [BSVoiceCell heightOfCell:model];
    }
    if ([model.type isEqualToString:@"51"]) {
        return 220;
    }
    return 0;
}




- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    BSHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    view.model = self.dataSource[section];
    view.nav = self.navigationController;
    return view;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 50;
}


//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//
//    BSFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer"];
//    view.model = self.dataSource[section];
//    view.nav = self.navigationController;
//    view.vc = self;
//    return view;
//}
//
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//
//    return 50;
//}


#pragma mark - 视频播放划出屏幕停止
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    PlayerManger *manager = [PlayerManger defaultManger];
    NSArray *arrayIndex = [self.tableView indexPathsForVisibleRows];
    if(manager.mediaType == Vedio){
     if (![arrayIndex containsObject:manager.indexPath]) {
        [manager.view removeFromSuperview];
        [manager stop];
     }
    }
}

//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
//        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}




@end
